package cacy.leetcode.array;


/**
 * @author 凯齐
 * @date 2025-02-21 13:29
 * @description
 */

class SolutionArray05 {
    public int[] spiralArray(int[][] array) {
        if (array.length == 0) {
            return new int[0];
        }
        int resIndex = 0, row = array.length, col = array[0].length;
        if (row == 1) {
            return array[0];
        }
        int[] res = new int[row * col];
        if (col == 1) {
            for (int i = 0; i < row; i++) {
                res[resIndex] = array[i][0];
                resIndex++;
            }
            return res;
        }
        int min = (row < col) ? row : col;
        for (int i = 0; i * 2 < min; i++) {
            if (i == min / 2) {
                if (row <= col) {
                    for (int jMid = i; jMid < col - i; jMid++) {
                        res[resIndex] = array[i][jMid];
                        resIndex++;
                    }
                }else {
                    for (int iMid = i; iMid < row - i; iMid++) {
                        res[resIndex] = array[iMid][i];
                        resIndex++;
                    }
                }
            }else {
                for (int jTop = i; jTop < col - i - 1; jTop++) {
                    res[resIndex] = array[i][jTop];
                    resIndex++;
                }
                for (int iRight = i; iRight < row - i - 1; iRight++) {
                    res[resIndex] = array[iRight][col - 1 - i];
                    resIndex++;
                }
                for (int jBottom = col - i - 1; jBottom > i; jBottom--) {
                    res[resIndex] = array[row - 1 - i][jBottom];
                    resIndex++;
                }
                for (int iLeft = row - i - 1; iLeft > i; iLeft--) {
                    res[resIndex] = array[iLeft][i];
                    resIndex++;
                }
            }
        }
        return res;
    }
}

public class Array05 {
    public static void main(String[] args) {
        int[][] array = {};
        int[] res = new SolutionArray05().spiralArray(array);
        for (int i = 0; i < res.length; i++) {
            System.out.print(res[i] + " ");
        }
    }
}
